<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog v-model="visible" :title="`${metadataId ? '编辑' : '创建'}`" :width="640"
    @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="140">
      <FormItem label="标题" prop="name">
        <Input v-model="formData.name" placeholder="请输入标题" />
      </FormItem>

      <FormItem label="顺序" prop="sortindex">
        <InputNumber :min="0" v-model="formData.sortindex" />
      </FormItem>

      <div class="flex_form_item flex-form">
        <FormItem label="禁用导入导出" prop="impfield">
          <Switch v-model="formData.impfield" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem label="生成ID" prop="pk">
          <Switch v-model="formData.pk" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>
      </div>

      <!-- <div class="flex_form_item flex-form"> -->
      <FormItem label="电话号码">
        <Switch v-model="formData.phonenumber" :true-value="1" :false-value="0">
          <template #open>
            <span>是</span>
          </template>
          <template #close>
            <span>否</span>
          </template>
        </Switch>
      </FormItem>

      <FormItem v-if="formData.phonenumber" label="号码类型">
        <Select v-model="formData.phonetype" transfer placeholder="请选择号码类型" filterable clearable>
          <Option v-for="item in optionsMap.phonetype.options" :value="item.id" :key="item.id">
            {{item.name}}
          </Option>
        </Select>
      </FormItem>
      <!-- </div> -->

      <div class="flex_form_item flex-form">
        <FormItem label="启用字典">
          <Switch v-model="formData.seldata" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem v-if="formData.seldata" label="字典项">
          <Select v-model="formData.seldatacode" transfer placeholder="请选择字典项" filterable clearable>
            <Option v-for="item in optionsMap.seldatacode.options" :value="item.id" :key="item.id">
              {{item.name}}
            </Option>
          </Select>
        </FormItem>
      </div>

      <div class="flex_form_item flex-form">
        <FormItem label="启用流程变量">
          <Switch v-model="formData.systemfield" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem v-if="formData.systemfield" label="启用多值">
          <Switch v-model="formData.modits" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>
      </div>

      <div class="flex_form_item flex-form">
        <FormItem label="启用关联">
          <Switch v-model="formData.reffk" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem v-if="formData.reffk" label="关联表">
          <Select v-model="formData.reftbid" transfer placeholder="请选择关联表">
            <Option v-for="item in ASSOCIATION_TABLE_OPTIONS" :value="item.value" :key="item.id">
              {{item.label}}
            </Option>
          </Select>
        </FormItem>
      </div>

      <FormItem label="数据校验">
        <CheckboxGroup v-model="formData.defaultvaluetitle">
          <Checkbox v-for="item in DATA_VAD_OPTIONS" :key="item.value" :label="item.value">
            {{ item.label }}</Checkbox>
        </CheckboxGroup>
      </FormItem>

      <FormItem label="转日期">
        <Switch v-model="formData.defaultfieldvalue" size="large" :true-value="1" :false-value="0">
          <template #open>
            <span>开启</span>
          </template>
          <template #close>
            <span>关闭</span>
          </template>
        </Switch>
      </FormItem>

      <FormItem label="数据处理">
        <RadioGroup v-model="formData.plugin">
          <Radio v-for="item in DATA_PRPCESSING_OPTIONS" :key="item.value" :label="item.value">
            {{ item.label }}</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem label="显示位置">
        <CheckboxGroup v-model="formData.viewtype">
          <Checkbox v-for="item in SHOW_ADDRESS_OPTIONS" :key="item.value" :label="item.value">
            {{ item.label }}</Checkbox>
        </CheckboxGroup>
      </FormItem>

      <div class="flex_form_item flex-form">
        <FormItem label="启用空值替换">
          <Switch v-model="formData.nullswitch" size="large" :true-value="1" :false-value="0">
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem v-if="formData.nullswitch" label="替换值">
          <Input v-model="formData.nullvalue" placeholder="请输入替换值" />
        </FormItem>
      </div>

      <FormItem label="HtmlFilter">
        <Switch v-model="formData.enablehtmlfilter" size="large" :true-value="1" :false-value="0">
          <template #open>
            <span>开启</span>
          </template>
          <template #close>
            <span>关闭</span>
          </template>
        </Switch>
      </FormItem>

      <FormItem label="启用条件关联导出值">
        <Switch v-model="formData.enableadvalue" size="large" :true-value="1" :false-value="0">
          <template #open>
            <span>开启</span>
          </template>
          <template #close>
            <span>关闭</span>
          </template>
        </Switch>
      </FormItem>

      <FormItem label="定制业务">
        <CheckboxGroup v-model="formData.customservice">
          <Checkbox v-for="item in BUSINESS_OPTIONS" :key="item.value" :label="item.value">
            {{ item.label }}</Checkbox>
        </CheckboxGroup>
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from 'view-ui-plus'
import {
  DATA_VAD_OPTIONS,
  DATA_PRPCESSING_OPTIONS,
  SHOW_ADDRESS_OPTIONS,
  ASSOCIATION_TABLE_OPTIONS,
  BUSINESS_OPTIONS
} from '@/util/conf'

import { metadata } from '@/api/modules/modelSetting'
import { sysdicGetByCode, sysdicIndex } from '@/api/modules/role'

const arrKeys = ['defaultvaluetitle', 'viewtype', 'customservice']
const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

// 元数据ID
const metadataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: '', //标题
  sortindex: 100, //顺序
  impfield: 0, //禁用导入导出
  pk: 0, //生成ID
  phonenumber: 0, //电话号码
  phonetype: '', //号码类型
  seldata: 0, //启用字典
  seldatacode: '', //字典项
  systemfield: 0, //启用流程变量
  modits: 0, //启用多值
  reffk: 0, //启用关联
  reftbid: '', //关联表
  defaultvaluetitle: [], //数据校验
  defaultfieldvalue: 0, //转日期
  plugin: null, //数据处理
  viewtype: [], //显示位置
  nullswitch: 0, //启用空值替换
  nullvalue: '', //替换值
  enablehtmlfilter: 0, //HtmlFilter
  enableadvalue: 0, //启用条件关联导出值
  customservice: [] //定制业务
})

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写标题', trigger: 'blur' }]
})

const optionsMap = ref({
  phonetype: {
    label: '号码类型',
    code: 'com.dic.phone.type',
    options: [],
    request: sysdicGetByCode
  },
  seldatacode: {
    label: 'JAVABean',
    options: [],
    request: sysdicIndex
  }
})

const getSelectData = () => {
  Object.entries(optionsMap.value).forEach(([key, item]) => {
    const params = {}
    if (item.code) {
      params.data = {
        code: item.code
      }
    }

    item.request(params).then(({ data }) => {
      // 将数据转换为OptionForm组件需要的格式
      item.options = data
    })
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const params = {
      ...formData.value,
      id: metadataId.value
    }

    arrKeys.forEach(key => {
      params[key] = formData.value[key].toString()
    })

    await metadata.propertiesEdit({
      data: params
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  metadata
    .propertiesDetail({
      data: {
        id: metadataId.value
      }
    })
    .then(({ data }) => {
      for (const key in formData.value) {
        if (arrKeys.includes(key)) {
          formData.value[key] = data[key] ? data[key].split(',') : []
          continue
        }

        if (typeof data[key] === 'boolean' || ['0', '1'].includes(data[key]) || data[key] === null) {
          formData.value[key] = +data[key]
          continue
        }

        formData.value[key] = data[key]
      }
    })
}

/**
 * 初始化对话框
 */
const initDialog = id => {
  // 显示对话框
  visible.value = true

  metadataId.value = id

  if (id) {
    getDetailData()
  }

  getSelectData()
}

defineExpose({
  initDialog
})
</script>

<style scoped lang="scss">
.ivu-form {
  height: 600px;
  overflow-y: auto;
}
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select {
  width: 240px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>